package com.kevin.design.creationalPattern.prototype;

import java.io.*;

public class DeepClone {
    public static void main(String[] args) throws CloneNotSupportedException {
        Prototype prototype = new Prototype("原型");
        prototype.setPrototype1(new Prototype1("附件"));
        Prototype prototypeClone = (Prototype) prototype.clone();
        System.out.println(prototype == prototypeClone);
        System.out.println(prototype.getPrototype1() == prototypeClone.getPrototype1());
    }
}

class Prototype1 implements Serializable{
    private String name;

    public Prototype1(String name) {
        this.name = name;
    }
}
class Prototype implements Cloneable,Serializable{
    private String name;
    private Prototype1 prototype1;

    public Prototype(String name) {
        this.name = name;
    }

    public Prototype1 getPrototype1() {
        return prototype1;
    }

    public void setPrototype1(Prototype1 prototype1) {
        this.prototype1 = prototype1;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // 序列化实现深度克隆
    @Override
    protected Object clone() throws CloneNotSupportedException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Object o = null;
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(this);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            o = objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return o;
    }

    @Override
    public String toString() {
        return "Prototype{" +
                "name='" + name + '\'' +
                ", prototype1=" + prototype1 +
                '}';
    }
}
